package top.forgirl.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.forgirl.domain.Material;
import top.forgirl.mapper.MaterialMapper;
import top.forgirl.util.StringGenerateUtil;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MaterialService {

    @Autowired
    private MaterialMapper materialMapper;

    public Material insertMaterial(String name, Double price) {
        name.replaceAll(" ", "");

        //同样是苹果，它可以是红富士
        List<Material> materials = materialMapper.select(name);

        List<Material> collect = materials.stream()
                .filter(material -> price.equals(material.getPrice()))
                .collect(Collectors.toList());
        if (collect.size() != 0) {
            return collect.get(0);
        }

        List<Integer> dIds = materialMapper.selectDid();
        String dId = StringGenerateUtil.generate4Did();
        while (dIds.contains(dId)) {
            dId = StringGenerateUtil.generate4Did();
        }

        Material material = new Material();
        material.setName(name);
        material.setPrice(price);
        material.setDId(dId);

        int result = materialMapper.insert(material);
        if (result > 0) {
            return material;
        } else {
            return null;
        }
    }
}
